package com.wallace.downloadserver.util

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.MediaType
import java.awt.PageAttributes
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 * @Description:
 * http相关的工具类
 * @author Wallace
 * @Date 2022/2/10 17:27
 */
object HttpUtil {

    private val log: Logger = LoggerFactory.getLogger(HttpUtil::class.java)

    /**
     * 获取用户真实IP地址，不使用request.getRemoteAddr()的原因是有可能用户使用了代理软件方式避免真实IP地址,
     * 可是，如果通过了多级反向代理的话，X-Forwarded-For的值并不止一个，而是一串IP值
     */
    fun getRealIp(request: HttpServletRequest): String {
        var ip: String? = request.getHeader("x-forwarded-for")
        if (ip != null && ip.isNotEmpty() && !"unknown".equals(ip, true)) {
            // 多次反向代理后会有多个ip值，第一个ip才是真实ip
            if (ip.indexOf(",") != -1) {
                ip = ip.split(",")[0]
                log.debug("x-forwarded-for-IP = $ip")
            }
        }
        if (ip == null || ip.isEmpty() || "unknown".equals(ip, true)) {
            ip = request.getHeader("Proxy-Client-IP")
            ip?.let { log.debug("Proxy-Client-IP = $it") }
        }
        if (ip == null || ip.isEmpty() || "unknown".equals(ip, true)) {
            ip = request.getHeader("WL-Proxy-Client-IP")
            ip?.let { log.debug("WL-Proxy-Client-IP = $it") }
        }
        if (ip == null || ip.isEmpty() || "unknown".equals(ip, true)) {
            ip = request.getHeader("HTTP_CLIENT_IP")
            ip?.let { log.debug("HTTP_CLIENT_IP = $it") }
        }
        if (ip == null || ip.isEmpty() || "unknown".equals(ip, true)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR")
            ip?.let { log.debug("HTTP_X_FORWARDED_FOR = $it") }
        }
        if (ip == null || ip.isEmpty() || "unknown".equals(ip, true)) {
            ip = request.getHeader("X-Real-IP")
            ip?.let { log.debug("X-Real-IP = $it") }
        }
        if (ip == null || ip.isEmpty() || "unknown".equals(ip, true)) {
            ip = request.remoteAddr
            ip?.let { log.debug("remoteAddr = $it") }
        }
        if (ip == null) {
            ip = "unknown"
            log.debug("ip = $ip")
        }
        return ip
    }

//    /**
//     * 返回错误信息
//     * @param response
//     * @param code 响应的HTTP状态码
//     * @param msg 错误信息
//     */
//    fun sendError(response: HttpServletResponse, code: Int, msg: String? = null) {
//        response.characterEncoding = Charsets.UTF_8.toString()
//        response.status = code
//        response.contentType = MediaType.TEXT_PLAIN_VALUE
//        msg?.apply {
//            response.writer.write(this)
//            response.writer.flush()
//            response.writer.close()
//        }
//    }
}